<template>
  <main-layout
    :showHome="!isFromList"
    :showBack="isFromList"
    :title="`${isEdit ? '修改' : '新增'}项目`"
  >
    <div class="form-box">
      <van-form @submit="onSubmit">
        <div class="title">基本信息</div>
        <van-field
          v-model="pageData.name"
          label="项目名"
          placeholder="输入项目名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <van-field
          v-model="pageData.signTime"
          label="签订日期"
          placeholder="选择签订日期"
          readonly
          :rules="[{ required: true, message: '选择签订日期' }]"
        >
          <template #button>
            <van-button
              type="primary"
              size="small"
              color="#ff5b02"
              @click="timeShow = true"
              native-type="button"
              >选择日期</van-button
            >
          </template>
        </van-field>
        <van-field
          readonly
          v-model="cityName"
          label="地市"
          placeholder="输入地级市"
          :rules="[{ required: true, message: '请选择地市' }]"
        >
          <template #button>
            <van-button
              type="primary"
              size="small"
              color="#ff5b02"
              @click="showPicker = true"
              native-type="button"
              >选择地市</van-button
            >
          </template>
        </van-field>
        <van-field
          v-model="pageData.address"
          label="详细地址"
          placeholder="输入详细地址"
          :rules="[{ required: true, message: '请输入详细地址' }]"
        />
        <van-field
          v-model="pageData.liableName"
          label="负责人"
          placeholder="选择负责人"
          :rules="[{ required: true, message: '请选择负责人' }]"
        >
          <template #button>
            <van-button
              type="primary"
              size="small"
              color="#ff5b02"
              @click="ClickPerson()"
              native-type="button"
              >选择负责人</van-button
            >
          </template>
        </van-field>
        <div class="title">业主信息</div>
        <van-field
          v-model="pageData.ownerName"
          label="业主"
          placeholder="请输入业主"
          :rules="[{ required: true, message: '请输入业主' }]"
        />
        <van-field
          v-model="pageData.ownerAddress"
          label="业主地址"
          placeholder="请输入业主地址"
          :rules="[{ required: true, message: '请输入业主地址' }]"
        />
        <van-field
          v-model="pageData.ownerPhone"
          label="联系电话"
          placeholder="请输入联系电话"
          :rules="[
            { required: true, message: '请输入联系电话' },
            {
              pattern: /^1[3-9]{1}[0-9]{9}$/,
              message: '输入正确的手机号',
              trigger: 'onBlur',
            },
          ]"
        />
        <div class="title">备注信息</div>
        <van-field
          v-model="pageData.remark"
          label="备注"
          placeholder="请输入备注信息"
        />
        <div style="margin: 16px">
          <van-button round block type="info" native-type="submit"
            >提交</van-button
          >
        </div>
      </van-form>
    </div>

    <van-calendar v-model="timeShow" @confirm="onConfirm" style="height: 60%" />
    <!--安装地市数据 -->
    <van-popup
      v-model="showPicker"
      :close-on-click-overlay="false"
      position="bottom"
    >
      <van-area
        title="选择地市"
        :area-list="areaList"
        @confirm="onConfirm1"
        @cancel="showPicker = false"
      />
    </van-popup>
    <!-- 选择负责人 -->
    <van-popup
      v-model="personShow"
      position="right"
      :style="{ height: '100%', width: '80%' }"
    >
      <div class="user-box">
        <header>
          <input type="text"  v-model="personObj.name" placeholder="请输入姓名" /><button type="info" @click="ClickPerson(true)">
            搜索
          </button>
        </header>
        <ul  @scroll="scrollEvt">
          <li v-for="it in personList" @click="chooseUser(it)"  :key="it.id" >
            {{it.name}}  {{it.dept}}  {{it.duties}}
          </li>
        <li  class="more">
          {{loading? "加载中" : hasMore ? "点击加载更多":"没有了，不要在滑了"}}
        </li>
        </ul>
      </div>
      <!-- close-on-click-overlay 点击弹出框之外 不关闭 -->
    </van-popup>
  </main-layout>
</template>
<script>
import { dateFormate } from "../../util";
// 下载的地市数据  cnpm i -S @vant/area-data
import { areaList } from "@vant/area-data";
import { personListApi, savaApi } from "../../apis/proApis.js";
export default {
  data() {
    return {
      isFromList: false,
      isEdit: false,
      pageData: {
        name: "",
        liableId: "",
        liableName: "",
        signTime: "",
        province: "",
        city: "",
        county: "",
        address: "",
        ownerId: "",
        ownerName: "",
        ownerAddress: "",
        ownerPhone: "",
        remark: "",
      },
      cityName: "",
      timeShow: false,
      personShow: false,
      showPicker: false,
      areaList,
      personList: [],
      //  负责人分页需要的
      personObj: {
        name: "",
        page: "1",
        size: "20",
      },
      loading:'loading',
      hasMore:true,
    };
  },
  created() {
    // query 路由传参
    this.isFromList = !!this.$route.query.from;
    this.isEdit = !!this.$route.query.id;
  },
  methods: {
 async   onSubmit() {
      console.log("ha-----ha----ha");
      let citys=this.cityName.split('/')
      this.pageData.province=citys[0]
      this.pageData.city=citys[1]
      this.pageData.county=citys[2]
      // 保存新建接口
      let result=await savaApi(this.pageData)
      console.log(result)
      if(result.code===200){
        this.$toast.success('保存成功')
        this.$router.go(-1)
      }else{
        this.$toast.fail('保存失败')

      }
    },
    // 选择时间
    onConfirm(date) {
      this.timeShow = false;
      this.pageData.signTime = dateFormate(date, "Y-M-d h:m:s");
    },
    //  选择地市
    onConfirm1(arr) {
      console.log(arr);
      this.showPicker = false;
      this.cityName = arr
        .reduce(function (res, item) {
          console.log("res是参数，后面的空数组", res);
          res.push(item.name);
          return res;
        }, [])
        .join("/");
      this.howPicker = false;
    },
    //打开负责人的弹框 选择负责人和 点击搜索（有参数传进来就是搜索，没有就是单机选择负责人按钮）
    // 用同一个方法是因为两个都要加载同一个列表数据
    ClickPerson(isQ) {
     console.log("isQ",isQ)
    //  传入参数时，就是点击搜索  重置列表
     this.personObj.page=1
     this.personList=[]
     console.log(this.personObj.name)
      // 发送数据请求
     this.getpersonList()
      if(!isQ){
        this.personObj.name=''
        this.personShow = true;
      }
    },
    // 获取用户数据的方法
   async getpersonList(){
     let result=await personListApi(this.personObj)
     console.log(result.data.rows)
     if(result.code===200){
        this.personList=this.personList.concat(result.data.rows)
         //  判断是否有下一页数据
        this.hasMore=this.personObj.page*this.personObj.size<result.data.total
     }
    //  因为vue是虚拟dom，而虚拟dom的更新和赋值是异步的，所有在关闭加载状态时，需要延迟
    setTimeout(()=>{
      this.loading=false
    })
   },
   scrollEvt(){
     let target=window.event.target
    //  判端是否到达底部
     let isBottom=(target.offsetHeight+target.scrollTop+20)>target.scrollHeight
    console.log('isB',isBottom)
    // 因为要节流（在第一次请求还没有结束时，不能发起第二次请求）
    if(!this.loading && this.hasMore && isBottom){
           this.loading=true
           this.personObj.page+=1
           this.getpersonList()
    }
   },
  //  选择确定负责人
   chooseUser(it){
     this.pageData.liableId=it.id
     this.pageData.liableName=it.name
     this.personShow=false
   }
  },
};
</script>
<style lang="less" scoped>
@import "../../style/common.less";
.form-box {
  height: 100%;
  padding: 4px 12px;
  .title {
    display: block;
    font-size: 0.8rem;
    padding: 12px 0;
  }
}
.user-box {
  display: block;
  height: 100%;
  > header {
    display: flex;
    padding: 8px 16px;
    border-bottom: 1px solid @cdd;
    input {
      flex: 1;
      padding: 0;
      line-height: 32px;
      font-size: 0.7rem;
      border: none;
      outline: none;
      color: @c99;
    }
    button {
      flex: 0 0 68px;
      height: 32px;
      color: @c99;
      border: none;
      font-size: 0.7rem;
      background-color: @primary;
    }
  }
  > ul {
    display: block;
    padding: 8px 16px;
    height: calc(100% - 32px);
    overflow-x: hidden;
    li {
      border-bottom: 1px solid #ddd;
      font-size: 0.7rem;
      padding: 10px;
      height: 30px;
      &:last-child {
        border-bottom: none;
      }
      &.more {
        text-align: center;
        color: @abc;
      }
    }
  }
}
</style>